package com.eplatform.modules.sys.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eplatform.common.service.CrudService;
import com.eplatform.common.utils.CacheUtils;
import com.eplatform.common.utils.DateUtils;
import com.eplatform.common.utils.SMSUtils;
import com.eplatform.modules.sys.dao.DictDao;
import com.eplatform.modules.sys.dao.SMSDao;
import com.eplatform.modules.sys.entity.Dict;
import com.eplatform.modules.sys.entity.SMS;
import com.eplatform.modules.sys.utils.DictUtils;
import com.google.common.collect.Maps;
//import com.taobao.api.ApiException;

/**
 * 短信发送Service
 * @author haolsh
 * @version 2016-08-10
 */
@Service
@Transactional(readOnly = true)
public class SMSService extends CrudService<DictDao, Dict> {
	@Autowired
	private SMSDao smsDao;
	
	@Transactional(readOnly = false)
	public Map sendSMS(Map p,HttpServletRequest request) //throws ApiException 
	{
		// TODO Auto-generated method stub
		SMS sms=new SMS();
		sms.setExtend("");
		String[] ps=(String[])p.get("pop_mobile");
		sms.setRecNum(ps[0]);
		sms.setSmscode(SMSUtils.randCode(4));
		Map result=SMSUtils.sendSMS(sms);
		boolean b=Boolean.parseBoolean(result.get("success").toString());
		if(b){
			Map params=Maps.newHashMap();
			params.put("id", java.util.UUID.randomUUID().toString());
			params.put("sms_recv", sms.getRecNum());
			params.put("sms_result",b?"1":"0");
			params.put("sms_send_ip", request.getLocalAddr());
			params.put("sms_send_id", request.getSession().getId());
			params.put("sms_content", sms.getSmscode());
			saveLog(params);
			request.getSession().setAttribute(SMSUtils.SESSIONKEY, sms.getSmscode());
		}
		return result;
	}
	@Transactional(readOnly = false)
	public void saveLog(Map m){
		smsDao.save(m);
	}
	public boolean checkStatus(HttpServletRequest request) {
		String sessionid=request.getSession().getId();
		String ip=request.getLocalAddr();
		Map params=Maps.newHashMap();
		params.put("sessionid", sessionid);
		params.put("ip", ip);
		Map result=smsDao.checkStatus(params);
		if(result==null)
			return true;
		Date sendDate= (Date)result.get("sendTime");
		Date now=new Date();
		long diff=now.getTime()-sendDate.getTime();
		if(diff/1000>60)
			return true;
		return false;
	}
	public boolean checkMobile(Map m){
		int count=smsDao.checkMobile(m);
		return count>0;
	}
	@Transactional(readOnly = false)
	public void modifyPwd(Map params) {
		// TODO Auto-generated method stub
		smsDao.modifyPwd(params);
	}
	
	

}
